package com.gitee.wsl.coroutines.strategy.hot

import com.gitee.wsl.base.Option
import com.gitee.wsl.base.empty
import com.gitee.wsl.base.get
import com.gitee.wsl.data.cache.Cache
import com.gitee.wsl.data.cache.memory
import kotlinx.atomicfu.AtomicInt
import kotlinx.atomicfu.atomic


typealias Policy<K> = (block:()->K) -> K

fun <T:Any> hotCall(policy: Policy<T> = QPS(5), block:()->T):T{
    return policy(block)
}

 class QPS<T:Any>(val value:Int): Policy<T> {
     override fun invoke(block: () -> T): T {
         var saveObject = cache.getOrPut(block){ atomic(0) to Option.empty<T>() }
         val qps = saveObject.first.incrementAndGet()
         if(value == qps) {
             val ret = block()
             saveObject = saveObject.first to Option(ret)
             cache[block] = saveObject
             return ret
         }else if(value>qps)
             return saveObject.second.get() as T
         return block()
     }

     companion object{
         val cache = Cache.memory<Any,Pair<AtomicInt,Option<Any>>>{
             this.setValidTime(1000)
         }
     }
 }

class Poll<T:Any>
